﻿using System;
using System.IO;
using System.Drawing.Imaging;
using SsrsRenderStudio.Shared.Windows32API;

namespace SsrsRenderStudio.Renderer.Output.Version2010
{
    public class DatabaseOutput: MetafileOutput
    {
        public DatabaseOutput(byte[][] renderReport) : base(renderReport) { }

        public override void Process()
        {
            WriteToDatabase();
        }

        public override void SetOptions(dynamic options)
        {
            // TODO: take in db conn, tbls, update/insert stmts here
        }

        public override dynamic GetOptions()
        {
            // TODO: return xref of metafile to db records
            return null;
        }

        private void WriteToDatabase()
        {
            try
            {
                for (int i = 0; i < _metafiles.Length; i++)
                {
                    Metafile a = FromByteArray(ToByteArray(_metafiles[i]));
                }
            }
            catch (Exception e)
            {
                Shared.Logger.WriteConsole("****DB OUTPUT EXCEPTION: " + e.Message);
            }
         
                   
        }

        private byte[] ToByteArray(Metafile mf)
        {
            int enhMetafileHandle = mf.GetHenhmetafile().ToInt32();
            int bufferSize = GDI.GetEnhMetaFileBits(enhMetafileHandle, 0, null); // Get required buffer size. 
            byte[] buffer = new byte[bufferSize]; // Allocate sufficient buffer 
            if (GDI.GetEnhMetaFileBits(enhMetafileHandle, bufferSize, buffer) <= 0) // Get raw metafile data. 
                throw new SystemException("GetEnhMetaFileBits Failed!");
            MemoryStream ms = new MemoryStream();
            ms.Write(buffer, 0, bufferSize);
            return ms.ToArray();
        }

        private Metafile FromByteArray(byte[] a)
        {
            MemoryStream ms = new MemoryStream(a);
            ms.Position = 0;
            return new Metafile((Stream)ms);
        }
    }
}
